<template>
    <div>
        <el-button
            type="primary"
            size="default"
            @click="addRole"
            style="margin-bottom: 10px"
            :disabled="
                (subjectStore.authority !== 1 && subjectStore.authority !== 0) || subjectStore.currentInfo.status !== 0
            "
        >
            添加成员
        </el-button>
        <el-table border :data="roleList" :fit="true">
            <el-table-column label="用户ID" align="center" prop="id"></el-table-column>
            <el-table-column label="用户名" align="center" prop="name"></el-table-column>
            <el-table-column label="发表日志数量" align="center" prop="logNums"></el-table-column>
            <el-table-column label="用户权限" align="center" prop="authority">
                <template #default="{ row }">
                    {{ authorityToRole(row.authority) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="{ row }">
                    <template v-if="row.id !== userStore.userId">
                        <el-button type="primary" size="default" @click="goUserDetail(row.id)">查看</el-button>
                        <template v-if="subjectStore.currentInfo.status === 0">
                            <el-button
                                type="danger"
                                size="default"
                                v-if="row.authority > subjectStore.authority"
                                @click="removeRole(row.id)"
                            >
                                移除该角色
                            </el-button>

                            <template v-if="subjectStore.authority === 0">
                                <el-button
                                    icon="Top"
                                    type="primary"
                                    size="default"
                                    v-if="row.authority === 2"
                                    @click="updateRole(row.id, 1)"
                                >
                                    设为管理员
                                </el-button>
                                <el-button
                                    icon="Bottom"
                                    type="primary"
                                    size="default"
                                    v-if="row.authority === 1"
                                    @click="updateRole(row.id, 2)"
                                >
                                    设为成员
                                </el-button>
                                <el-button type="primary" size="default" @click="setChairman(row.id)">
                                    设为负责人
                                </el-button>
                            </template>
                        </template>
                    </template>
                    <template v-else>
                        <el-button
                            type="danger"
                            size="default"
                            @click="quitSubject"
                            v-if="subjectStore.currentInfo.status === 0"
                        >
                            退出课题
                        </el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <user-drawer v-model:visible="visible" :userId="curUserId" />
        <el-dialog v-model="roleDialog" title="添加角色" @closed="dialogClosed" :close-on-click-modal="false">
            <template #default>
                <el-form label-width="auto" ref="ruleFormRef">
                    <el-form-item label="成员" prop="mamberIds">
                        <role-select v-model="mamberIds" style="width: 50%"></role-select>
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-button type="primary" size="default" @click="submit">添加成员</el-button>
                        <el-button type="primary" size="default" @click="roleDialog = false">关闭窗口</el-button>
                    </el-form-item>
                </el-form>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import useSubjectStore from "@/store/modules/subject";
import useUserStore from "@/store/modules/user";
import useLayOutSettingStore from "@/store/modules/setting";
import { ElMessage, ElMessageBox } from "element-plus";
import { RoleCode, RoleName, RoleNameType } from "@/constants/role";
import { reqAddRole, reqRemoveRole, reqUpdateRole, reqSetChairman, reqQuitSubject } from "@/api/role";
// 引入组件
import RoleSelect from "./RoleSelect/index.vue";
import { storeToRefs } from "pinia";
// 获取仓库
const subjectStore = useSubjectStore();
const userStore = useUserStore();

const { roleList } = storeToRefs(subjectStore);

// 页面打开时就获取对应的信息
subjectStore.getRoleList();
// 控制用户抽屉的显示
const visible = ref(false);
const curUserId = ref(-1);

// 查看用户详情
const goUserDetail = (userId: number) => {
    visible.value = true;
    curUserId.value = userId;
};

// 将权限等级转为职位
const authorityToRole = (authority: number) => {
    return RoleName[RoleCode[authority] as RoleNameType];
};

// 添加角色面板
const roleDialog = ref(false);
// 添加角色列表
const mamberIds = ref<Array<number>>([]);
// 点击添加角色
const addRole = () => {
    roleDialog.value = true;
};
// 提交添加角色表单
const submit = async () => {
    const mamberArr = mamberIds.value.map((mamber) => {
        return {
            subjectId: +subjectStore.currentId,
            mamberId: mamber,
            authority: 2,
        };
    });
    const result = await reqAddRole({ mamberArr });
    if (result.code === 200) {
        ElMessage.success("添加成功");
        // 关闭弹窗
        roleDialog.value = false;
        // 获取列表
        subjectStore.getRoleList();
    } else {
        ElMessage.error(result.data);
    }
};
// 表单关闭前清空数据
const dialogClosed = () => {
    mamberIds.value = [];
};

// 删除角色
const removeRole = async (mamberId: number) => {
    try {
        await ElMessageBox.confirm("确认删除该角色吗？", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
        });
    } catch (error) {
        return;
    }

    const result = await reqRemoveRole({
        subjectId: +subjectStore.currentId,
        mamberId,
    });
    if (result.code === 200) {
        ElMessage.success("删除成功");
        // 获取列表
        subjectStore.getRoleList();
    } else {
        ElMessage.error(result.data);
    }
};

// 设置权限
const updateRole = async (mamberId: number, authority: number) => {
    try {
        await ElMessageBox.confirm("确认修改该角色的身份吗？", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
        });
    } catch (error) {
        return;
    }
    const result = await reqUpdateRole({
        subjectId: +subjectStore.currentId,
        mamberId,
        authority,
    });
    if (result.code === 200) {
        ElMessage.success("修改成功");
        // 获取列表
        subjectStore.getRoleList();
    } else {
        ElMessage.error(result.data);
    }
};

// 修改负责人
const setChairman = async (mamberId: number) => {
    try {
        await ElMessageBox.confirm("确认修改负责人吗？", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
        });
    } catch (error) {
        return;
    }
    const result = await reqSetChairman({
        subjectId: +subjectStore.currentId,
        mamberId,
    });
    if (result.code === 200) {
        ElMessage.success("修改成功");
        // 获取列表
        subjectStore.getRoleList();
        // 应该重新获取身份
        subjectStore.getAuthority();
    } else {
        ElMessage.error(result.data);
    }
};

// 退出课题
const layOutSettingStore = useLayOutSettingStore();
const quitSubject = async () => {
    if (subjectStore.authority === 0) {
        ElMessage.error("请先转让负责人或刷新页面之后再尝试退出课题");
        return;
    }
    const result = await reqQuitSubject({
        subjectId: +subjectStore.currentId,
    });

    if (result.code === 200) {
        ElMessage.success("退出成功");
        // 跳回第一页
        layOutSettingStore.refresh = !layOutSettingStore.refresh;
    } else {
        ElMessage.error(result.data);
    }
};
</script>

<style lang="scss" scoped></style>
